﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace twilters
{
    /// <summary>
    /// Interaction logic for LoginWindow.xaml
    /// </summary>
    public partial class LoginWindow : Window
    {
        private TwitterClient client;
        private DataStore dataStore;
        private MainWindow mainWindow;

        public int returnValue;
        public static int IDOK = 1;
        public static int IDCANCEL = -1;

        public LoginWindow(MainWindow mainWindow, TwitterClient client, DataStore dataStore, PrivateData privateData)
        {
            InitializeComponent();

            this.mainWindow = mainWindow;
            this.client = client;
            this.dataStore = dataStore;

            rememberPassword.IsChecked = false;
            if (privateData != null)
            {
                LoginUsername.Text = privateData.Username;
                LoginPassword.Password = privateData.Password;
                if (privateData.Username != null && privateData.Password != null && privateData.Username.Length > 0 && privateData.Password.Length > 0)
                {
                    rememberPassword.IsChecked = true;
                }
                else
                {
                    rememberPassword.IsChecked = false;
                }
            }
        }

        private void DoLogin_Click(object sender, RoutedEventArgs e)
        {
            String username = LoginUsername.Text;
            String password = LoginPassword.Password;

            if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(username))
            {
                WindowUtil.displayError("Credentials not filled");
            }

            PrivateData privateData = dataStore.loadPrivateData();
            if ((bool)rememberPassword.IsChecked)
            {
                privateData.Username = username;
                privateData.Password = password;
            }
            else
            {
                privateData.Username = "";
                privateData.Password = "";
            }
            dataStore.storePrivateData(privateData);

            client.loginAndInitialize(username, password);
            if (client.isLogged())
            {
                mainWindow.Refresh();
                Close();
            }
            else
            {
                WindowUtil.displayError("Login failed");
            }
        }

        private void CancelLogin_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
